package com.atguigu4;

import com.beans.ExamStudent;
import com.utils.JDBCUtils;
import org.junit.Test;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * 课后练习er:
 *  代码1实现插入一个新的Student信息
 *  代码2实现，在idea中建立程序，输入身份证号或者准考证号可以查询到学生的基本信息
 *  代码3实现，完成学生的删除功能
 * @auther user
 * @date 2021/12/7 - 15:55
 */
public class Exer2Test {
    //针对于各个表的通用更新操作
    public int update(String sql,Object ...args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            //1 获取连接
            connection = JDBCUtils.getConnection();
            //2 预编译sql,返回preparedStatment实例
            preparedStatement = connection.prepareStatement(sql);
            //3 填充占位符
            for (int i = 0; i < args.length; i++) {
                preparedStatement.setObject(i + 1, args[i]);
            }
            //4 执行更新操作，返回影响的条目数
            int i = preparedStatement.executeUpdate();
            return i;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //5 关闭资源
            JDBCUtils.closeResource(connection, preparedStatement);
        }
        return 0;
    }
    //代码1实现插入一个新的Student信息
    @Test
    public void testInsertExamstudent(){
        String sql = "insert into examstudent(Type,IDCard,ExamCard,StudentName,Location,Grade) values(?,?,?,?,?,?)";
        //请输入考试类型（4四级/6六级）：
        String type = "4";
        //请输入身份证号：
        String IDCard = "123456789";
        //请输入准考证号：
        String examCard ="123456789";
        //请输入学生姓名：
        String studentName = "颤三";
        //请输入区域（城市）
        String locaion = "背景";
        //请输入成绩：
        String grade = "32";
        int updateCount = update(sql, type, IDCard, examCard, studentName, locaion, grade);
        if (updateCount == 1){
            System.out.println("添加成功");
        }else {
            System.out.println("添加失败");
        }
    }
    //针对于各个表的通用查询操作
    public <T> T getInstance(Class<T> clazz,String sql,Object ...args){
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            //1 获取连接
            connection = JDBCUtils.getConnection();
            //2 预编译sql,返回preparedStatement实例
            preparedStatement = connection.prepareStatement(sql);
            //3 填充占位符
            for (int i = 0; i < args.length; i++) {
                preparedStatement.setObject(i+1,args[i]);
            }
            //4 执行，返回ResultSet结果集
            resultSet = preparedStatement.executeQuery();
            //5 处理结果集
            //获取元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            //获取总列数
            int columnCount = metaData.getColumnCount();
            if (resultSet.next()){
                T t = clazz.newInstance();
                for (int i = 0; i < columnCount; i++) {
                    //获取列别名
                    String columnLabel = metaData.getColumnLabel(i + 1);
                    //获取列值
                    Object columnValue = resultSet.getObject(i + 1);
                    //通过反射将columnValue存储进clazz类对象的columnLabel属性中
                    Field field = clazz.getDeclaredField(columnLabel);
                    field.setAccessible(true);
                    field.set(t,columnValue);
                }
                return t;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //6 关闭资源
            JDBCUtils.closeResource(connection,preparedStatement,resultSet);
        }
        return null;
    }
    //代码2实现，在idea中建立程序，输入身份证号或者准考证号可以查询到学生的基本信息
    @Test
    public void testGetInstance(){
        Scanner scanner = new Scanner(System.in);
        System.out.println("请选择你输入的类型，a 身份证号/b 准考证号:");
        String type = scanner.nextLine();
        String sql = null;
        ExamStudent examStudent = null;
        switch (type){
            case "a":
                sql = "select Type as type,IDCard as IDCard,ExamCard as examCard,StudentName as studentName,Location as location,Grade as grade from examstudent where IDCard = ?";
                System.out.println("请输入身份证号：");
                String IDCard = scanner.nextLine();
                IDCard = "612524199809170682";
                examStudent = getInstance(ExamStudent.class, sql, IDCard);
                break;
            case "b":
                sql = "select Type as type,IDCard as IDCard,ExamCard as examCard,StudentName as studentName,Location as location,Grade as grade from examstudent where ExamCard = ?";
                System.out.println("请输入准考证号：");
                String examCard = scanner.nextLine();
                examCard = "200523164754005";
                examStudent = getInstance(ExamStudent.class, sql, examCard);

                break;
            default:
                System.out.println("输入有误");
                break;
        }
        if (examStudent != null){
            System.out.println("examStudent = " + examStudent);
        }else {
            System.out.println("查无此人");
        }
    }
    //针对于各个表的通用查询操作 返回list
    public <T> List<T>  getForList(Class<T> clazz, String sql, Object ...args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            //1 获取连接
            connection = JDBCUtils.getConnection();
            //2 预编译sql,返回preparedStatment实例
            preparedStatement = connection.prepareStatement(sql);
            //3 填充占位符
            for (int i = 0; i < args.length; i++) {
                preparedStatement.setObject(i+1,args[i]);
            }
            //4 执行，返回ResultSet结果集
            resultSet = preparedStatement.executeQuery();
            //5 处理结果集
            //获取元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            //获取总列数
            int columnCount = metaData.getColumnCount();
            //创建结果List
            ArrayList<T> arrayList = new ArrayList<T>();
            while (resultSet.next()){
                T t = clazz.newInstance();
                for (int i = 0; i < columnCount; i++) {
                    //获取列的别名
                    String columnLabel = metaData.getColumnLabel(i+1);
                    //获取列值
                    Object columnValue = resultSet.getObject(i + 1);
                    //通过反射，将columnValue存储到Clazz对象的columnLabel属性中
                    Field field = clazz.getDeclaredField(columnLabel);
                    field.setAccessible(true);
                    field.set(t,columnValue);
                }
                arrayList.add(t);
            }
            return arrayList;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //6关闭资源
            JDBCUtils.closeResource(connection,preparedStatement,resultSet);
        }
        return null;
    }
    @Test
    public void testGetForList(){
        String sql = "select Type as type,IDCard as IDCard,ExamCard as examCard,StudentName as studentName,Location as location,Grade as grade from examstudent where FlowID < ?";
        List<ExamStudent> list = getForList(ExamStudent.class, sql, 10);
        list.forEach(System.out::println);
    }
}
